﻿using System;
using System.Collections.Generic;
using System.Linq;

using WpfAdmin.Everything.Enums;

namespace WpfAdmin.Everything.Queryable {
    internal class NameQueryable : Queryable, INameQueryable {
        private string pattern;
        private string startWith;
        private string endWith;
        private string extensions;
        public NameQueryable(IQueryGenerator parent)
            : base(parent) {
            this.Flags = RequestFlags.FullPathAndFileName;
        }

        public IQuery Contains(string pattern) {
            this.pattern = this.QuoteIfNeeded(pattern);
            return new Query(this);
        }

        public IQuery StartWith(string pattern) {
            this.startWith = this.QuoteIfNeeded(pattern);
            return new Query(this);
        }

        public IQuery EndWith(string pattern) {
            this.endWith = this.QuoteIfNeeded(pattern);
            return new Query(this);
        }

        public IQuery Extension(string extension) {
            if (extension.Contains(".")) {
                throw new ArgumentException("Do not specify the dot character when specifying an extension");
            }

            this.extensions = extension;
            return new Query(this);
        }

        public IQuery Extensions(IEnumerable<string> extensions) {
            return this.ExtensionCollection(extensions);
        }

        public IQuery Extensions(params string[] extensions) {
            return this.ExtensionCollection(extensions);
        }
        private IQuery ExtensionCollection(IEnumerable<string> newExtensions) {
            if (newExtensions == null) {
                throw new ArgumentNullException(nameof(newExtensions));
            }
            if (!newExtensions.Any()) {
                throw new ArgumentException("The list of exceptions must not be empty");
            }
            if (newExtensions.Any(x => x.Contains("."))) {
                throw new ArgumentException("Do not specify the dot character when specifying an extension");
            }

            return this.Extension(string.Join(";", newExtensions));
        }

        public override IEnumerable<string> GetQueryParts() {
            foreach (var queryPart in base.GetQueryParts()) {
                yield return queryPart;
            }

            if (!string.IsNullOrEmpty(this.startWith)) {
                yield return $"startwith:{this.startWith}";
            }

            if (!string.IsNullOrEmpty(this.pattern)) {
                yield return this.pattern;
            }

            if (!string.IsNullOrEmpty(this.endWith)) {
                yield return $"endwith:{this.endWith}";
            }

            if (!string.IsNullOrEmpty(this.extensions)) {
                yield return $"ext:{this.extensions}";
            }
        }
    }
}
